package org.sun.onepink.ui.home

import android.Manifest
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.PropertyValuesHolder
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.baidu.aip.speech.AipSpeech
import org.json.JSONException
import org.json.JSONObject
import org.sun.onepink.R
import org.sun.onepink.databinding.FragmentHomeBinding
import org.sun.onepink.utils.AudioRecorder

class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!
    private val homeViewModel: HomeViewModel by viewModels()
    private var animatorSet: AnimatorSet? = null
    private lateinit var asrClient: AipSpeech // 百度语音识别客户端
    private var audioRecorder: AudioRecorder? = null

    // 使用新的权限请求方式替代已弃用的方法
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            startVoiceRecognition()
        } else {
            // Permission denied
            if (shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO)) {
                // Show an explanation to the user
                AlertDialog.Builder(requireContext())
                    .setTitle("需要录音权限")
                    .setMessage("此应用需要录音权限来进行语音识别，请授予权限。")
                    .setPositiveButton("重试") { _, _ ->
                        requestAudioPermission()
                    }
                    .setNegativeButton("取消", null)
                    .show()
            } else {
                // User has permanently denied the permission, direct them to app settings
                AlertDialog.Builder(requireContext())
                    .setTitle("需要录音权限")
                    .setMessage("请在应用设置中手动授予权限。")
                    .setPositiveButton("前往设置") { _, _ ->
                        openAppSettings()
                    }
                    .setNegativeButton("取消", null)
                    .show()
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 初始化百度语音识别客户端
        asrClient = AipSpeech(
            "119785928",  // 从百度云控制台获取
            "CaUzS21zTAoZY1jOCpHAtHln", // 从百度云控制台获取
            "p2s0HNuJtzS8HK2uvhHxuSFFms6VVA9f" // 从百度云控制台获取
        )

        binding.voiceIcon.setOnClickListener {
            if (checkAudioPermission()) {
                startVoiceRecognition()
            } else {
                requestAudioPermission()
            }
        }
    }

    private fun checkAudioPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            requireContext(),
            Manifest.permission.RECORD_AUDIO
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun requestAudioPermission() {
        requestPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
    }

    private fun openAppSettings() {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
            data = Uri.fromParts("package", requireContext().packageName, null)
        }
        startActivity(intent)
    }

    private fun startVoiceRecognition() {
        // 1. 启动动画
        startVoiceAnimation()

        // 2. 开始语音识别
        Thread {
            try {
                // 设置识别参数
                val options = HashMap<String, Any>()
                options["dev_pid"] = 1537 // 普通话输入法模型
                Log.e("JSONCheck", "✅ JSON库兼容性验证通过Aaaaa")
//                JSONObject::class.java.getConstructor(Object::class.java)
                Log.i("JSONCheck", "✅ JSON库兼容性验证通过")
                println("开始初始化识别")

                // 3. 开始录音并识别
                val res = asrClient.asr(
                    recordAudio(), // 录音方法
                    "wav",       // 语音格式
                    16000,       // 采样率
                    options      // 识别参数
                )
                println("初始化成功")

                // 4. 处理识别结果
                requireActivity().runOnUiThread {
                    stopVoiceAnimation()
                    handleRecognitionResult(res.toString())
                }
            } catch (e: Exception) {
                requireActivity().runOnUiThread {
                    stopVoiceAnimation()
                    binding.textHome.text = "识别失败: ${e.message}"
                    binding.textHome.setTextColor(Color.RED)
                    Toast.makeText(requireContext(), "识别失败: ${e.message}", Toast.LENGTH_LONG).show()
                }
            }
        }.start()
    }

    private fun recordAudio(): ByteArray {
        audioRecorder = AudioRecorder(requireContext())
        audioRecorder?.startRecording()
        // 录音3秒
        Thread.sleep(3000)

        return audioRecorder?.stopRecording() ?: ByteArray(0)
    }

    private fun handleRecognitionResult(result: String) {
        try {
            println("识别结果：" + result)
            val json = result;// JSONObject(result)
            if (json!=null) {
                val text = result;//json.getJSONArray("result").getString(0)
                binding.textHome.text = "识别结果: $text"
                binding.textHome.setTextColor(Color.parseColor("#00FF00"))

                // 同时更新EditText
                binding.inputBox.setText(text)
            } else {
                binding.textHome.text = "未识别到语音"
                binding.textHome.setTextColor(Color.RED)
            }
        } catch (e: JSONException) {
            binding.textHome.text = "结果解析失败"
            binding.textHome.setTextColor(Color.RED)
        }
    }

    private fun startVoiceAnimation() {
        if (binding.voiceIcon.background !is GradientDrawable) {
            binding.voiceIcon.setBackgroundResource(R.drawable.circle_glow)
        }

        binding.textHome.text = "正在聆听..."
        binding.textHome.setTextColor(Color.parseColor("#B388FF"))

        val scaleAnim = ObjectAnimator.ofPropertyValuesHolder(
            binding.voiceIcon,
            PropertyValuesHolder.ofFloat("scaleX", 1.2f),
            PropertyValuesHolder.ofFloat("scaleY", 1.2f)
        ).apply {
            duration = 800
            repeatCount = ObjectAnimator.INFINITE
            repeatMode = ObjectAnimator.REVERSE
        }

        // Create color animation using a ValueAnimator and manually updating the drawable
        val colorAnim = android.animation.ValueAnimator.ofObject(
            android.animation.ArgbEvaluator(),
            Color.parseColor("#00FFFB"),
            Color.parseColor("#FF00FF")
        ).apply {
            duration = 1200
            repeatCount = ObjectAnimator.INFINITE
            repeatMode = ObjectAnimator.REVERSE
            addUpdateListener { animator ->
                val color = animator.animatedValue as Int
                (binding.voiceIcon.background as? GradientDrawable)?.setStroke(8, color)
            }
        }

        animatorSet = AnimatorSet().apply {
            playTogether(scaleAnim, colorAnim)
            start()
        }
    }

    private fun stopVoiceAnimation() {
        animatorSet?.cancel()
        binding.voiceIcon.scaleX = 1f
        binding.voiceIcon.scaleY = 1f
        (binding.voiceIcon.background as? GradientDrawable)?.setStroke(
            8,
            Color.parseColor("#00FFFB")
        )
    }
    override fun onDestroyView() {
        animatorSet?.cancel()
        audioRecorder?.release()
        _binding = null

        super.onDestroyView()
    }
}